package com.fanxuankai.boot.monitor.prometheus;

import com.fanxuankai.boot.monitor.Message;
import com.fanxuankai.boot.monitor.Monitor;
import com.fanxuankai.boot.monitor.Notifier;
import com.fanxuankai.commons.util.Prometheus;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author fanxuankai
 */
public class PrometheusMonitor implements Monitor {
    @Resource
    private PrometheusProperties properties;
    @Resource
    private Notifier<Message> notifier;
    private static final String SUCCESS = "success";

    @Override
    public String title() {
        return properties.getTitle();
    }

    @Override
    public String cron() {
        return properties.getCron();
    }

    @Override
    public void exec() throws IOException {
        for (PrometheusProperties.PrometheusConfig config : properties.getConfigs()) {
            Prometheus.Client client = new Prometheus.Client(config.getUrl());
            List<String> contents = new ArrayList<>(config.getQueries().size());
            for (PrometheusProperties.PrometheusConfig.Query query : config.getQueries()) {
                Prometheus.Result.Vector vector = client.query(query.getText());
                if (vector == null || !SUCCESS.equals(vector.getStatus())) {
                    contents.add(String.format("%s: %s", query.getText(), "获取 Metrics 失败"));
                    continue;
                }
                vector.getData()
                        .getResult()
                        .stream()
                        .findFirst()
                        .ifPresent(result -> {
                            float value = result.getValue().get(result.getValue().size() - 1);
                            if (value > query.getThreshold()) {
                                contents.add(String.format("%s: %ss", query.getText(), value));
                            }
                        });
            }
            if (!contents.isEmpty()) {
                Message message = new Message();
                message.setTitle(properties.getTitle());
                message.setSubtitle(Optional.ofNullable(properties.getSubtitle())
                        .orElse(config.getUrl()));
                message.setContents(contents);
                notifier.notice(message);
            }
        }
    }
}
